package websocket

import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer


fun main(args: Array<String>) {
    val server = MockWebServer()

    server.enqueue(MockResponse().withWebSocketUpgrade(object : WebSocketListener() {

        override fun onOpen(webSocket: WebSocket, response: Response) {
            println("server onOpen")
            println("server request header:" + response.request().headers())
            println("server response header:" + response.headers())
            println("server response:" + response)
        }

        override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response) {
            //出现异常会进入此回调
            System.out.println("server onFailure")
            System.out.println("throwable:" + t)
            System.out.println("response:" + response)
        }

        override fun onClosing(webSocket: WebSocket, code: Int, reason: String?) {
            System.out.println("server onClosing")
            System.out.println("code:" + code + " reason:" + reason)

        }

        override fun onMessage(webSocket: WebSocket, text: String) {
            System.out.println("server onMessage")
            System.out.println("message:" + text)
            //接受到5条信息后，关闭消息定时发送器
//                if (msgCount == 5) {
//                    mTimer.cancel()
//                    webSocket.close(1000, "close by server")
//                    return
//                }
            webSocket.send("response-" + text)
        }

        override fun onClosed(webSocket: WebSocket, code: Int, reason: String?) {
            System.out.println("server onClosed")
            System.out.println("code:" + code + " reason:" + reason)
        }
    }))

//    hostName:localhost and port:38922
    println("hostName:${server.hostName} and port:${server.port}")

}